var k = 0;
var g = 0;

//定义变量获取屏幕视口宽度
var windowWidth = $(window).width();
if(windowWidth < 992){
    // do something
    k = "100%";
    g = "46%";
}
if(windowWidth >= 992){
    // do something
    k = "500px";
    g = "345px";
}


//JavaScript代码区域
layui.use(['element', 'layer', 'jquery'], function () {
    var element = layui.element;
    var layer = layui.layer;
    var $ = layui.jquery;

    //layer.msg("layui-我的网盘");

    //------------------------------------------【init】-------------------------------------------
    document.oncontextmenu = function () {
        return false
    };

    //------------------------------------------【data】-------------------------------------------
    var that = {
        currentPath: "",
        rootPath: "",
        separator: "/",
        downloadPath: "",
        delPath: ""
    }

    //------------------------------------------【event】-------------------------------------------
    $(".mobile-btn").click(function () {
        if ($(".layui-side").css("left") == "0px") {
            $(".layui-side").removeClass("show-layui-side");
        } else {
            $(".layui-side").addClass("show-layui-side");
        }
    });

    // 点击下载文件
    $(".download").click(function () {
        window.open("/file/downLoad/" + that.downloadPath);
        layer.closeAll();
    });

    // 点击选择文件
    $(".upload").click(function () {
        $("#fileName1").click();

    });

    // 选中文件自动上传，然后刷新列表
    $("#fileName1").change(function () {
        var formData = new FormData();//这里需要实例化一个FormData来进行文件上传
        formData.append("file", $("#fileName1")[0].files[0]);
        layer.load();
        $.ajax({
            type: "post",
            url: "/file/uploadFiles",
            data: formData,
            processData: false,
            contentType: false,
            headers: {
                "path": that.currentPath
            },
            success: function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    field.openPath(that.currentPath);
                    $("#fileName1")[0].files[0] = null;
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            }
        });
    });


    // 删除文件到回收站
    $(".del").click(function () {
        // console.log(that.delPath);
        // var delPath = $(this).attr("path");
        $.ajax({
            url: "/file/del",
            type: "get",
            dataType: "json",
            data: "",
            headers: {
                "delPath": encodeURI(that.delPath)
            },
            success: function (res) {
                if (res.code == 200) {
                    layer.msg(res.msg, {icon: 1});
                    field.openPath(that.currentPath);
                } else {
                    layer.msg(res.msg, {icon: 2});
                }
            },
            error: function (res) {
                layer.msg("请求服务器出错", {icon: 5});
            },
            complete: function () {
                setTimeout(function () {
                    layer.closeAll();
                }, 1000);
            }
        });
    });

    // 清空回收站
    $(".clear-recycle_bin").click(function () {
        layer.open({
            title: "提示",
            content: "将永久删除文件，无法找回，确定删除吗？",
            anim: 6,
            icon: 7,
            btn: ["狠心删除", "取消"],
            yes: function (index) {
                $.ajax({
                    url: "/file/clear",
                    type: "get",
                    dataType: "json",
                    data: "",
                    headers: {},
                    success: function (res) {
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    },
                    error: function (res) {
                        layer.msg("请求服务器出错", {icon: 5});
                    },
                    complete: function () {
                        setTimeout(function () {
                            layer.closeAll();
                        }, 1000);
                    }
                });
                layer.close(index);
            },
            ntn2: function (index2) {
                layer.close(2);
            }
        });
    });

    //创建文件夹
    $(".mkdir").click(function () {
        layer.open({
            title: "创建文件夹",
            type: 1,
            content: $("#mkdirForm"),
            btn: ["创建", "取消"],
            yes: function (index) {
                layer.load();
                var name = $("#mkdirForm input").val().trim();
                if (!name) {
                    layer.msg("请输入文件名", {icon: 2});
                    return false;
                }
                var pre = encodeURI(that.currentPath);

                console.log(pre);
                $.ajax({
                    url: "/file/mkdir",
                    type: "get",
                    dataType: "json",
                    data: "",
                    headers: {
                        "mkdirPath": pre + encodeURI(name)
                    },
                    success: function (res) {
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                            field.openPath(that.currentPath);
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    },
                    error: function (res) {
                        layer.msg("请求服务器出错", {icon: 5});
                    },
                    complete: function () {
                        setTimeout(function () {
                            layer.closeAll();
                        }, 1000);
                    }
                });
            }
        });
    });

    // 新建文件
    $(".touch").click(function () {
        layer.open({
            title: "新建文件",
            type: 1,
            content: $("#touchForm"),
            btn: ["新建", "取消"],
            yes: function (index) {
                layer.load();
                var name = $("#touchForm input").val().trim();
                if (!name) {
                    layer.msg("请输入文件名", {icon: 2});
                    return false;
                }
                if(name.indexOf(".")==-1){
                    name = name+".txt";
                }
                var pre = encodeURI(that.currentPath);
                $.ajax({
                    url: "/file/touch",
                    type: "get",
                    dataType: "json",
                    data: "",
                    headers: {
                        "touchPath": pre + encodeURI(name)
                    },
                    success: function (res) {
                        if (res.code == 200) {
                            layer.msg(res.msg, {icon: 1});
                            field.openPath(that.currentPath);
                        } else {
                            layer.msg(res.msg, {icon: 2});
                        }
                    },
                    error: function (res) {
                        layer.msg("请求服务器出错", {icon: 5});
                    },
                    complete: function () {
                        setTimeout(function () {
                            layer.closeAll();
                        }, 1000);
                    }
                });
            }
        });
    });


    // 按分类显示文件
    $(".byType dd").click(function () {
        var text = $(this).attr("type");
        console.log(text);
        $.ajax({
            url:"/file/getFileListByType/"+text,
            type:"get",
            dataType:"json",
            data:"",
            headers:{},
            success:function(res){
                console.log(res);
                if(res.code==200){
                    $("#searchTimeOut").text(res.msg);
                    var list = res.data;

                    $(".separator").remove();
                    $(".mianbaoxie").remove();
                    $(".layui-breadcrumb").append('<a path="' + that.rootPath + '" class="mianbaoxie" href="javascript:;"></a>');
                    createDOM(list);
                }else{
                    layer.msg(res.msg,{icon:2});
                }
            },
            error:function(res){
                layer.msg("请求服务器出错",{icon:5});
            },
            complete:function(){
                setTimeout(function(){
                    layer.closeAll();
                },1000);
            }
        });
    });

    //点击按名称搜索
    $(".pc-searchText").click(function(){
        var str = $("#search").val();
        if(!str.trim()){
            return false;
        }
        search(str);
    });

    //回车搜索
    $('#search').bind('keydown', function (event) {
        var event = window.event || arguments.callee.caller.arguments[0];
        if (event.keyCode == 13){
            // 来了，在这里写 回车之后要干的事
            var str = $("#search").val();
            if(!str.trim()){
                return false;
            }
            search(str);
        }
    });

    // 退出登陆
    $(".loginout").click(function(){
        loginOut();
    });

    //------------------------------------------【methods】-------------------------------------------
    // 请求


    // 文件操作对象
    var field = {
        getRootPath: function () {
            $.get("/file/getRootPath", "", function (res) {
                that.rootPath = res.data;
                that.currentPath = that.rootPath;
                field.openPath(that.currentPath, null);
            });
        },
        openPath: function (path, fileName) {
            $.ajax({
                url: "/file/list",
                type: "get",
                dataType: "json",
                data: "",
                headers: {
                    "openPath": path
                },
                success: function (res) {

                    if (res.code == 200) {
                        that.currentPath = path;
                        if (fileName) {
                            $(".separator").remove();
                            $(".mianbaoxie").remove();
                            $(".layui-breadcrumb").append('<a path="' + that.rootPath + '" class="mianbaoxie" href="javascript:;"></a>');
                            var pathStr = decodeURI(path).replace(that.rootPath, "");
                            var pathList = pathStr.split(that.separator);
                            var basePath = that.rootPath;
                            for (var i = 0; i < pathList.length; i++) {
                                if (pathList[i]) {
                                    basePath = basePath + encodeURI(pathList[i]) + that.separator;
                                    $(".layui-breadcrumb").append('<span class="separator" lay-separator>&gt;</span><a path="' + basePath + '" class="mianbaoxie" href="javascript:;">' + pathList[i] + '</a>');
                                }
                            }

                            element.render('layui-breadcrumb');
                            $(".mianbaoxie").click(function () {
                                var path = $(this).attr("path");
                                var name = $(this).text();
                                openDirectory(path, name);
                            });
                        }
                        $(".file-item").remove();
                        var list = res.data;

                        // 创建DOM
                        createDOM(list);
                    } else {
                        layer.msg(res.msg, {icon: 2});
                    }
                },
                error: function (res) {
                    layer.msg("请求服务器出错", {icon: 5});
                },
                complete: function () {
                    setTimeout(function () {
                        layer.closeAll();
                    }, 1000);
                }
            });
        }
    }
    var openDirectory = function (path, name) {
        field.openPath(path, name);
    }
    init();

    function init() {
        field.getRootPath();
    }

    /**
     * 那到文件集合，创建DOM
     */
    function createDOM(list){

        $(".file-item").remove();

        if(!list){
            $("#searchTimeOut").text("无结果");
            return false;
        }
        if(list.length<1){
            $("#searchTimeOut").text("无结果");
            return false;
        }




        var html = '';
        for (var i = 0; i < list.length; i++) {
            html += '<div class="file-item" path="' + (list[i].fileURL + that.separator) + '" suffix="' + list[i].suffix + '">\n';

            if (list[i].suffix == "jpg" || list[i].suffix == "png" || list[i].suffix == "jpeg" || list[i].suffix == "gif") {
                html += '<img class="file-icon" src="' + list[i].icon + '">\n';
            } else {
                html += '<img class="file-icon" src="/static/image/icon/' + list[i].icon + '">\n';
            }
            html += '<p class="file-name">' + list[i].fileName + '</p>\n' +
                '                    <div class="file-tips">\n' +
                '                        <p class="fileName">文件名:' + list[i].fileName + '</p>\n' +
                '                        <p class="fileSize">大小：' + list[i].size + '</p>\n' +
                '                        <p class="directory">类型：' + (list[i].isDirectory == "true" ? "文件夹" : "文件") + '</p>\n' +
                '                        <p class="createTime">时间：' + list[i].updateTime + '</p>\n' +
                '                    </div>\n' +
                '                </div>';
        }
        $(".file-box").append(html);


        // ********************点击某个文件、或文件夹
        $(".file-item").mousedown(function (e) {
            // alert(e.which)
            e.preventDefault(); // 阻止默认行为
            var isDirectory = $(this).find(".directory").text();
            var suffix = $(this).attr("suffix");
            var path = encodeURI($(this).attr("path"));
            var fileName = $(this).find(".file-name").text();
            if (e.which == 1) {
                // 是文件夹，打开文件夹，获取文件列表
                if (isDirectory == "类型：文件夹") {

                    // var file = encodeURI(fileName);

                    field.openPath(path, fileName);
                } else {
                    switch (suffix) {
                        case "jpg":
                        case "png":
                        case "jpeg":
                        case "gif":
                            // 预览图片操作
                            var photoJSON = {
                                "title": "", //相册标题
                                "id": 123, //相册id
                                "start": index, //初始显示的图片序号，默认0
                                "data": [   //相册包含的图片，数组格式
                                ]
                            };

                            var index = 0;
                            var temp = 0;
                            var itemList = $(".file-item");
                            for (var i = 0; i < itemList.length; i++) {
                                var path2 = encodeURI($(itemList[i]).attr("path"));

                                var suf = $(itemList[i]).attr("suffix");
                                var name = $(itemList[i]).find(".fileName").text();
                                var src = $(itemList[i]).find(".file-icon").attr("src");


                                if (suf == 'jpg' || suf == 'png' || suf == 'jpeg' || suf == 'gif') {
                                    photoJSON.data.push({
                                        "alt": name,
                                        "src": src, //原图地址
                                        "thumb": "" //缩略图地址
                                    });
                                    if (path == path2) {
                                        index = temp;
                                    }
                                    temp++;
                                }
                            }
                            photoJSON.start = index;
                            layer.photos({
                                photos: photoJSON
                                , anim: 5 //0-6的选择，指定弹出图片动画类型，默认随机（请注意，3.0之前的版本用shift参数）
                            });

                            break;
                        case "txt":
                        case "html":
                        case "js":
                        case "css":
                        case "java":
                        case "py":
                        case "md":
                        case "xml":
                        case "gitignore":
                        case "":
                            $.ajax({
                                url: "/file/readFileStr",
                                type: "get",
                                dataType: "json",
                                data: "",
                                headers: {
                                    "readPath": path
                                },
                                success: function (res) {
                                    if (res.code == 200) {
                                        $("#preCode code").addClass(suffix);
                                        var highCode = hljs.highlightAuto(res.data).value;
                                        $("#preCode code").html(highCode);

                                        // setTimeout(function(){
                                        //
                                        // },2000);
                                        // 编辑和预览文本操作
                                        layer.open({
                                            title: "查看内容"
                                            , area: ['100%', '100%']
                                            , type: 1
                                            , shadeClose: true
                                            , content: $("#preCode")
                                        });

                                    } else {
                                        layer.msg(res.msg, {icon: 2});
                                    }
                                },
                                error: function (res) {
                                    layer.msg("请求服务器出错", {icon: 5});
                                },
                                complete: function () {

                                }
                            });
                            break;
                        case "mp4":
                        case "3gp":
                        case "MOV":
                            layer.open({
                                title: "播放视频",
                                type: 1,
                                area: [k, g],
                                content: $("#video")
                                , shade: 0.8
                                , shadeClose: true
                                , end: function () {
                                    //右上角关闭回调
                                    $("#video video")[0].pause();
                                    //return false 开启该代码可禁止点击该按钮关闭
                                }
                            });
                            var reg=/\\|\//g;
                            var videoPath = encodeURI(path.replace(reg,"^"));
                            $("#video video").attr("src", "/file/playVideo/" + videoPath);
                            $("#video video")[0].play();
                            break;
                        case "mp3":
                        case "wav":
                            layer.open({
                                title: "播放音频",
                                type: 1,
                                area: ['auto', '100px'],
                                content: $("#audio")
                                , shade: 0.8
                                , shadeClose: true
                                , end: function () {
                                    //右上角关闭回调
                                    $("#audio audio")[0].pause();
                                    //return false 开启该代码可禁止点击该按钮关闭
                                }
                            });
                            var reg=/\\|\//g;
                            var audioPath = encodeURI(path.replace(reg,"^"));
                            $("#audio audio").attr("src", "/file/playAudio/" + audioPath);
                            $("#audio audio")[0].play();
                            break;
                    }
                }
            } else if (e.which == 2) {

            } else if (e.which == 3) {
                var x = e.pageX + "px";
                var y = e.pageY + "px";
                if (isDirectory == "类型：文件夹") {
                    if (fileName == "回收站") {
                        layer.open({
                            title: "操作",
                            closeBtn: 0,
                            icon: 1,
                            type: 1,
                            offset: [y, x],
                            shadeClose: true,
                            content: $("#rightClick_3")
                        });
                    } else {
                        layer.open({
                            title: "操作",
                            closeBtn: 0,
                            type: 1,
                            offset: [y, x],
                            shadeClose: true,
                            content: $("#rightClick_1")
                        });
                    }

                } else {
                    layer.open({
                        title: "操作",
                        closeBtn: 0,
                        type: 1,
                        offset: [y, x],
                        shadeClose: true,
                        content: $("#rightClick_2")

                    });
                }
                // var downloadPath = path.replace(that.separator,"^");
                var reg=/\\|\//g;
                var current1 = path.substring(0, path.length - 1);
                console.log(current1);
                var current2 = decodeURI(current1);
                console.log(current2);
                var current3 = current2.replace(reg,"^");
                console.log(current3);
                that.downloadPath = current3;
                that.delPath = current3;
            }
            return false;
        });
    }


    function search(str){
        $.ajax({
            url:"/file/search/"+str,
            type:"get",
            dataType:"json",
            data:"",
            headers:{},
            success:function(res){
                if(res.code==200){
                    $("#searchTimeOut").text(res.msg);

                    $(".separator").remove();
                    $(".mianbaoxie").remove();
                    $(".layui-breadcrumb").append('<a path="' + that.rootPath + '" class="mianbaoxie" href="javascript:;"></a>');
                    var list = res.data;
                    createDOM(list);
                }else{
                    layer.msg(res.msg,{icon:2});
                }
            },
            error:function(res){
                layer.msg("请求服务器出错",{icon:5});
            },
            complete:function(){
                setTimeout(function(){
                    layer.closeAll();
                },1000);
            }
        });
    }


    function loginOut() {
        console.log("退出登陆");
        sessionStorage.clear("userSession");
        window.location = "/login.html";
    }


});
